<?php

namespace app\middleware;

use think\Request;
use think\Response;
use app\model\User;
use Closure;

class Auth
{
    /**
     * 处理请求
     */
    public function handle(Request $request, Closure $next)
    {
        // 获取Token
        $token = $this->getToken($request);

        if (!$token) {
            return $this->unauthorized('请先登录');
        }

        // 验证Token
        $payload = verifyJWT($token);
        if (!$payload) {
            return $this->unauthorized('Token无效或已过期');
        }

        // 检查用户是否存在且正常
        $user = User::find($payload['user_id']);
        if (!$user) {
            return $this->unauthorized('用户不存在');
        }

        if ($user->status != 1) {
            return $this->unauthorized('账号已被禁用');
        }

        // 将用户ID注入请求
        $request->userId = $user->id;
        $request->user = $user;

        // 更新用户活跃时间（可选，频率可控制）
        $this->updateUserActivity($user->id, $request);

        return $next($request);
    }

    /**
     * 获取Token
     */
    private function getToken(Request $request)
    {
        // 优先从Header获取
        $authorization = $request->header('Authorization');
        if ($authorization && preg_match('/Bearer\s+(.*)$/i', $authorization, $matches)) {
            return $matches[1];
        }

        // 从参数获取
        return $request->param('token');
    }

    /**
     * 返回未授权响应
     */
    private function unauthorized($message = '未授权访问')
    {
        return json([
            'code' => 401,
            'message' => $message,
            'data' => null,
            'timestamp' => time()
        ])->code(401);
    }

    /**
     * 更新用户活跃时间
     */
    private function updateUserActivity($userId, Request $request)
    {
        // 这里可以实现缓存机制，避免每次请求都更新数据库
        // 例如：只有距离上次更新超过5分钟才更新
        $cacheKey = "user_activity_{$userId}";
        $lastUpdate = cache($cacheKey);

        if (!$lastUpdate || (time() - $lastUpdate) > 300) { // 5分钟
            // 更新用户最后活跃时间
            User::where('id', $userId)->update(['last_login_at' => date('Y-m-d H:i:s')]);

            // 更新设备活跃时间
            $deviceId = $request->param('device_id');
            if ($deviceId) {
                \app\model\UserDevice::where('user_id', $userId)
                    ->where('device_id', $deviceId)
                    ->update([
                        'last_active' => date('Y-m-d H:i:s'),
                        'ip_address' => $request->ip(),
                        'user_agent' => $request->header('user-agent'),
                    ]);
            }

            // 更新缓存
            cache($cacheKey, time(), 300);
        }
    }
}